/*****************************************************************************
 * Copyright (C) Stacy Curl. All rights reserved.                            *
 * ------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the BSD      *
 * style license a copy of which has been included with this distribution in *
 * the LICENSE.txt file.                                                     *
 *****************************************************************************/
package picounit.features.classloader;

import java.util.StringTokenizer;

public class PackageUtil {
	public String packageName(Class aClass) {
		Package startingPackage = aClass.getPackage();

		return startingPackage != null ? startingPackage.getName() :
			packageName(aClass.getName()); 
	}

	public String defaultPackage() {
		return "[default package]";
	}
	
	public int sourceDepth(Class aClass) {
		String packageName = packageName(aClass);
	
		return packageName.equals(defaultPackage()) ? 1 :
			1 + new StringTokenizer(packageName, ".").countTokens();
	}

	///////////////////////////////////////////////////////////////////////////////////////////////
	// Implementation methods
	///////////////////////////////////////////////////////////////////////////////////////////////

	private String packageName(String className) {
		int positionOfLastDot = className.lastIndexOf('.');

		return positionOfLastDot == -1 ? defaultPackage() :
			className.substring(0, positionOfLastDot);
	}
}
